﻿using System;
using System.Windows.Forms;
using WF = System.Windows.Forms;

namespace UpwardsTimeClock.Prototype
{
    public class TimerControl : VisualControlBase<Timer>
    {
        private static readonly DateTime _midnight = new DateTime(2000, 1, 1);
        private WF.Label _label;
        private DateTime _startDateTime;
        private TimeSpan _startTimeSpan;
        private TimeSpan _endTimeSpan;

        public TimerControl(Timer config)
            : base(config)
        {
            _label = LabelControl.CreateLabel(config);
        }

        protected override Control CreateVisualControl()
        {
            return _label;
        }

        public override void Start()
        {
            _startDateTime = DateTime.Now;
            _startTimeSpan = TimeSpan.Parse(Config.StartValue);
            _endTimeSpan = TimeSpan.Parse(Config.EndValue);
            base.Start();

            UpdateTimer();
        }

        private void UpdateTimer()
        {
            TimeSpan passed = 
                Program.GetScaledDisplayTimeSpan(DateTime.Now - _startDateTime);
            TimeSpan timerSpan;

            if (Config.CountMode == TimerCountMode.Up)
            {
                timerSpan = _startTimeSpan + passed;
                if (timerSpan >= _endTimeSpan) timerSpan = _endTimeSpan;
            }
            else
            {
                timerSpan = _startTimeSpan - passed;
                if (timerSpan <= _endTimeSpan) timerSpan = _endTimeSpan;
            }

            DateTime timerTime = _midnight + timerSpan;
            string formattedTimer = timerTime.ToString(Config.Text);
            _label.Text = formattedTimer;
            _label.Refresh();
        }

        public override void Timer()
        {
            base.Timer();
            UpdateTimer();
        }

        public override void AdjustStartTime(TimeSpan adjustment)
        {
            _startDateTime += adjustment;
        }
    }
}
